#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "commtraff.h"
#include "commtraff_socket_client.h"



#include "commtraff_hilog.h"



#define BUFFER_SIZE 1024 * 1024


static pthread_t g_clientThread = 0;
static int g_clientFd = -1;
static char *g_clientBuffer = NULL;
static ClientRecvCb g_clientCb;
static int g_clientRunning = 0;
static int g_clientPort = 0; // 保存客户端端口


void *ClientRecvThreadFunc(void *arg)
{
    struct sockaddr_in serverAddr;
    socklen_t serverAddrLen;

    LOGI("Client receive thread start");
    
    serverAddrLen = sizeof(serverAddr);
    
    while (g_clientRunning) {
        serverAddrLen = sizeof(serverAddr);
        memset(g_clientBuffer, 0, BUFFER_SIZE);

        // Receive data from server
        ssize_t bytesRead = recvfrom(g_clientFd, g_clientBuffer, BUFFER_SIZE - 1, 0,
                                      (struct sockaddr *)&serverAddr, &serverAddrLen);

        if (bytesRead > 0) {
            if (g_clientCb.OnRecv) {
                g_clientCb.OnRecv(g_clientBuffer, bytesRead);
            }
        } else if (bytesRead < 0 && g_clientRunning) {
            if (errno != EAGAIN && errno != EWOULDBLOCK) {
                LOGE("Failed to receive data from server: %zd, errno=%d, msg=%s", bytesRead, errno, strerror(errno));
            }
        }
    }
    if (g_clientFd != -1) {
        close(g_clientFd);
        g_clientFd = -1;
    }
    LOGI("Client receive thread exit");
    return NULL;
}

int32_t ClientInit(ClientRecvCb *cb)
{
    g_clientBuffer = (char *)malloc(BUFFER_SIZE);
    if (g_clientBuffer == NULL) {
        LOGE("Failed to allocate memory for client buffer");
        return COMMTRAFF_FAIL;
    }
    memset(g_clientBuffer, 0, BUFFER_SIZE);
    
    g_clientCb = *cb;
    
    // Create UDP socket for client
    g_clientFd = socket(AF_INET, SOCK_DGRAM, 0);
    if (g_clientFd == -1) {
        LOGE("Failed to create client UDP socket: %s", strerror(errno));
        free(g_clientBuffer);
        g_clientBuffer = NULL;
        return COMMTRAFF_FAIL;
    }
    
    // 设置端口复用
    int opt = 1;
    if (setsockopt(g_clientFd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
        LOGE("Failed to set SO_REUSEADDR option: %s", strerror(errno));
        close(g_clientFd);
        free(g_clientBuffer);
        g_clientBuffer = NULL;
        return COMMTRAFF_FAIL;
    }
    
    // 绑定客户端套接字以获取端口
    struct sockaddr_in clientAddr;
    socklen_t clientAddrLen = sizeof(clientAddr);
    memset(&clientAddr, 0, sizeof(clientAddr));
    clientAddr.sin_family = AF_INET;
    clientAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    clientAddr.sin_port = htons(0); // 让内核自动分配端口
    
    if (bind(g_clientFd, (struct sockaddr *)&clientAddr, sizeof(clientAddr)) == -1) {
        LOGE("Failed to bind client socket: %s", strerror(errno));
        close(g_clientFd);
        free(g_clientBuffer);
        g_clientBuffer = NULL;
        return COMMTRAFF_FAIL;
    }
    
    // 获取分配的端口
    if (getsockname(g_clientFd, (struct sockaddr *)&clientAddr, &clientAddrLen) == -1) {
        LOGE("Failed to get client port: %s", strerror(errno));
        close(g_clientFd);
        free(g_clientBuffer);
        g_clientBuffer = NULL;
        return COMMTRAFF_FAIL;
    }
    
    g_clientPort = ntohs(clientAddr.sin_port);

    g_clientRunning = 1;
    
    // Start client receive thread
    int result = pthread_create(&g_clientThread, NULL, ClientRecvThreadFunc, NULL);
    if (result != 0) {
        LOGE("Failed to create client receive thread: %d", result);
        g_clientRunning = 0;
        close(g_clientFd);
        free(g_clientBuffer);
        g_clientBuffer = NULL;
        return COMMTRAFF_FAIL;
    }
    
    return COMMTRAFF_SUCCESS;
}

int32_t SendDataToServer(uint8_t *buffer, int32_t length)
{
    if (buffer == NULL) {
        LOGE("buffer is null");
        return COMMTRAFF_FAIL;
    }

    struct sockaddr_in serverAddr;
    int sendFd = g_clientFd;  // 默认使用全局fd
    int tempFdCreated = 0;    // 标记是否创建了临时fd


    // 如果g_clientFd == -1，则手动创建临时fd
    if (sendFd == -1) {
        LOGD("g_clientFd == -1, creating temporary socket for sending");
        // 创建临时UDP socket
        sendFd = socket(AF_INET, SOCK_DGRAM, 0);
        if (sendFd == -1) {
            LOGE("Failed to create temporary UDP socket: %s", strerror(errno));
            return COMMTRAFF_FAIL;
        }
        
        // 尝试绑定到任意可用端口以确保socket可用
        struct sockaddr_in tempAddr;
        memset(&tempAddr, 0, sizeof(tempAddr));
        tempAddr.sin_family = AF_INET;
        tempAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
        tempAddr.sin_port = htons(0);  // 让系统自动分配端口
        
        if (bind(sendFd, (struct sockaddr *)&tempAddr, sizeof(tempAddr)) == -1) {
            LOGE("Failed to bind temporary socket: %s", strerror(errno));
            close(sendFd);
            return COMMTRAFF_FAIL;
        }
        
        tempFdCreated = 1;
    }

    // Set server address
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);  // localhost
    serverAddr.sin_port = htons(COLLECTD_SERVER_PORT);

    // Send data to server using sendto
    ssize_t bytesSent = -1;
    int retryTimes = 3;
    do {
        bytesSent = sendto(sendFd, buffer, length, 0,
                            (struct sockaddr *) &serverAddr, sizeof(serverAddr));
        retryTimes--;
    } while (bytesSent < 0 && retryTimes > 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR));

    // 如果创建了临时fd，发送完成后立即shutdown并关闭
    if (tempFdCreated) {
        LOGD("Shutting down and closing temporary socket");
        shutdown(sendFd, SHUT_RDWR);
        close(sendFd);
    }

    if (bytesSent < 0) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            LOGE("Socket would block, try again later");
        } else {
            LOGE("Failed to send data to server: %s", strerror(errno));
        }
        return COMMTRAFF_FAIL;
    }

    return COMMTRAFF_SUCCESS;
}

int32_t ClientDeinit()
{
    g_clientRunning = 0;
    
    // 等待接收线程结束
    if (g_clientThread != 0) {
        pthread_join(g_clientThread, NULL);
        g_clientThread = 0;
    }
    
    if (g_clientBuffer) {
        free(g_clientBuffer);
        g_clientBuffer = NULL;
    }
    
    g_clientPort = 0; // 重置客户端端口
    
    return COMMTRAFF_SUCCESS;
}

// 获取客户端端口的函数
int32_t GetClientPort(void)
{
    return g_clientPort;
}